﻿package com.shawnblais.utils
{
    import flash.display.*;
    import flash.events.*;
    import flash.utils.*;

    public class FramerateMonitor extends MovieClip
    {
        private var _frameCount:Number = 1;
        private var _timer:Timer;
        private var _currentFPS:Object;
        private var _previousTimer:Object;
        public var refreshRate:Number;

        public function FramerateMonitor(param1:Number = 0.2)
        {
            if (param1 < 0.05)
            {
                this.refreshRate = 0.05;
            }
            else
            {
                this.refreshRate = param1;
            }
            this._previousTimer = getTimer();
            this._timer = new Timer(this.refreshRate * 1000);
            this._timer.addEventListener(TimerEvent.TIMER, this.calculateFramerate);
            this._timer.start();
            addEventListener(Event.ENTER_FRAME, this.incrementCount);
            return;
        }// end function

        private function incrementCount(event:Event)
        {
            var _loc_2:String = this;
            _loc_2._frameCount = this._frameCount++;
            return;
        }// end function

        public function get framerate()
        {
            return this._currentFPS;
        }// end function

        private function calculateFramerate(event:TimerEvent)
        {
            this._currentFPS = Math.floor(this._frameCount / ((getTimer() - this._previousTimer) / 1000));
            this._frameCount = 0;
            this._previousTimer = getTimer();
            return;
        }// end function

        public function getFramerate() : Number
        {
            return this._currentFPS;
        }// end function

        public function Destroy()
        {
            this._currentFPS = 0;
            this._timer.stop();
            this._timer.removeEventListener(TimerEvent.TIMER, this.calculateFramerate);
            removeEventListener(Event.ENTER_FRAME, this.incrementCount);
            if (this.parent)
            {
                this.parent.removeChild(this);
            }
            return;
        }// end function

    }
}
